package cn.uai.activiti8.approval.cmd;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.cmd.NeedsActiveTaskCmd;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 查询 taskId 节点上的历史 UserTask
 * @author uai
 * @since 2025/7/21 22:33
 * @version 1.0
 */
public class QueryHistoryUserTaskCmd extends NeedsActiveTaskCmd<List<Map<String, String>>> {

    private static final long serialVersionUID = -2640865880039727272L;

    private static final Logger LOGGER = LoggerFactory.getLogger(QueryHistoryUserTaskCmd.class);

    private static final String USER_TASK = "userTask";

    public QueryHistoryUserTaskCmd(String taskId) {
        super(taskId);
    }


    @Override
    protected List<Map<String, String>> execute(CommandContext commandContext, TaskEntity task) {
        String activityId = task.getExecution().getActivityId();
        HistoryService historyService = commandContext.getProcessEngineConfiguration().getHistoryService();
        List<HistoricActivityInstance> userTaskHistoricActivities = historyService.createHistoricActivityInstanceQuery()
                                                                                    .processInstanceId(task.getProcessInstanceId())
                                                                                    .activityType(USER_TASK)
                                                                                    .orderByHistoricActivityInstanceId()
                                                                                    .asc()
                                                                                    .list();
        List<Map<String, String>> mapList = userTaskHistoricActivities
                                                    .stream()
                                                    .filter(h -> !activityId.equals(h.getActivityId()))
                                                    .map(hai -> {
                                                        Map<String, String> map = new HashMap<>();
                                                        map.put("activityId", hai.getActivityId());
                                                        map.put("activityName", hai.getActivityName());
                                                        return map;
                                                    }).toList();
        LOGGER.info("查询到 taskId [{}] 对应的历史 UserTask: {}", taskId, mapList);
        return List.copyOf(mapList);
    }
}
